package com.bodu.global.log;

import cn.hutool.core.date.DateUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.bodu.global.security.LoginUser;
import com.bodu.system.entity.request.LoginLogRequest;
import com.bodu.system.service.LoginLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Objects;

/**
 * 用户登录成功监听器事件
 *
 * @author chqiuu
 */
@Slf4j
@Component
public class LoginSuccessLogSupport implements ApplicationListener<AuthenticationSuccessEvent> {

    private final LoginLogService loginLogService;

    public LoginSuccessLogSupport(LoginLogService loginLogService) {
        this.loginLogService = loginLogService;
    }

    /**
     * 用户通过输入用户名和密码登录成功
     * 登录账号
     *
     * @param event 验证成功监听事件
     */
    @Override
    public void onApplicationEvent(AuthenticationSuccessEvent event) {
        LoginLogRequest loginLogRequest = new LoginLogRequest();
        LoginUser loginUser = (LoginUser) event.getAuthentication().getPrincipal();
        loginLogRequest.setUserName(loginUser.getUsername());
        loginLogRequest.setIp(ServletUtil.getClientIP(Objects.requireNonNull(((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()), ""));
        loginLogRequest.setStatusFlag(0);
        loginLogRequest.setCreateUser(loginUser.getId());
        loginLogRequest.setCreateTime(DateUtil.date());
        loginLogRequest.setLoginMsg("登录成功");
        loginLogService.save(loginLogRequest);
    }
}
